//
//  HomeTableView.swift
//  maosheng
//
//  Created by lxl on 2019/8/17.
//

import UIKit

class HomeTableView: PublicSwiftTableView {
    let bannerHeight = CGFloat(180)
    let cycleView = ZCycleView()
    var str_url = "api/services/app/Blog/GetBlogPagingListAsync"//推荐
    var currentIndex = 1
    let cellIdentifer = "MyCollectCell"
    let noImgIdentifer = "MyCollectNoImgCell"
    let oneImgIdentifer = "MyBlogOneImageCell"

    
    var params = [String : Any]()
    var searchText : String?
    var didUpdateTopList : TableViewRefresh?
    override init(frame: CGRect) {
        super.init(frame: frame)
        tableView.separatorStyle = .singleLine
//        self.loop
        self.getTheHomeNewsList(isHeader: true)
        getTheHomeBanner()
        tableView.register(MyCollectCell.self, forCellReuseIdentifier: cellIdentifer)
        tableView.register(MyCollectNoImgCell.self, forCellReuseIdentifier: noImgIdentifer)
        tableView.register(MyBlogOneImageCell.self, forCellReuseIdentifier: oneImgIdentifer)

        refreshList = {[weak self] (isHeader) in
            if self?.didUpdateTopList != nil {
                self?.didUpdateTopList!(isHeader)
            }
          self?.getTheHomeNewsList(isHeader: isHeader)
        }
        setCyclyeViewType()
    }
    func setCyclyeViewType(){
        cycleView.isInfinite = true
        cycleView.isAutomatic = true
        cycleView.itemSize = CGSize(width: SCREENW - 40, height: bannerHeight)
        cycleView.itemSpacing = 5
        cycleView.timeInterval = 5
        cycleView.itemCornerRadius = 10
        cycleView.scrollDirection = .horizontal
        cycleView.backgroundColor = TABLE_LINE_COLOR
    }
    func setHomeParams(index : Int )  {
//        let tmpView = UIView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 0))
//        tableView.tableHeaderView?.removeFromSuperview()
//        tableView.tableHeaderView = nil
//        currentIndex = index
        params.removeValue(forKey: "AreaCodes")
        params.removeValue(forKey: "KeyWords")

        switch index {
        case 1:
            params["Sorting"] = "isTop desc,isEssential desc,id desc"
            getTheHomeBanner()

        case 2:
            params["Sorting"] = "viewCount desc"

        case 3:
            params["Sorting"] = "id desc"
            let shared = MapManager.shareInstance() as? MapManager
            
            if let areaCode = shared?.adCode{
//                if areaCode.count
                params["AreaCodes"] = areaCode

            }

        default:
            params["Sorting"] = "id desc"
            print("")
        }
        if let text = searchText {
            params["KeyWords"] = text
        }
        params["PageIndex"] = pageIndex
        params["PageSize"] = 10

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //    MARK:-推荐banner
    func getTheHomeBanner() -> Void {
        
        SDataCenter.shared.SGetJsonDataWithUrl(str_url: "api/services/app/Recommend/GetRecommendItemPagingListAsync", params: ["sorting" : "id desc"]) { [weak self] (responseData, isSuccess) in
         
            
            if isSuccess && responseData is [String : Any]{
            
                if let items = (responseData as! [String : Any])["items"]{
                    if let arr = items as? Array<Any>{
                        if let attentionArr = [HomeNavModel].deserialize(from: arr){
//                            self?.dataSource.addObjects(from: attentionArr as [Any])
                            self?.setBannerImgs(bannerArr: attentionArr as! [HomeNavModel])
                        }
                    }
                    
                }
              
            }else{
               
                
            }
        }
    }
    func setBannerImgs(bannerArr : [HomeNavModel])  {
        var imgUrls = [String]()
        for model in bannerArr{
            if let url = model.imageUrl{
                imgUrls.append(url)
            }
            
        }
//        cycleView.itemZoomScale = 1.2

//        imgUrls.append(imgUrls.first!)
        cycleView.setUrlsGroup(imgUrls)
        cycleView.frame = CGRect(x: 0, y: 0, width: SCREENW, height: bannerHeight)
        cycleView.pageControlIsHidden = true

//        tableView.tableHeaderView = cycleView


    }
   
    //MARK:-首页列表
    func getTheHomeNewsList(isHeader : Bool) -> Void {
        if isHeader{
            self.pageIndex = 1
        }
        self.setHomeParams(index: self.currentIndex)

        SDataCenter.shared.SGetJsonDataWithUrl(str_url: str_url, params: params) { [weak self] (responseData, isSuccess) in
            if self?.tableView.mj_header != nil{
                self?.tableView.mj_header.endRefreshing()
                self?.tableView.mj_footer.endRefreshing()
            }
            
            if isSuccess && responseData is [String : Any]{
                if isHeader{
                    self?.dataSource.removeAllObjects()
                }
                if let items = (responseData as! [String : Any])["items"]{
                    if let arr = items as? Array<Any>{
                        if let attentionArr = [CollectModel].deserialize(from: arr){
                            self?.dataSource.addObjects(from: attentionArr as [Any])
                        }
                    }
                    
                }
                if self?.dataSource.count == 0{
                    ProgressHUD.showMsgWithoutView("暂无数据")
                }
//                self?.checkNeedNoDataView()
                self?.setRefreshFooter()
            }else{
                if !isHeader{
                    self?.pageIndex = self!.pageIndex - 1
                }
                
            }
        }
    }
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return currentIndex == 1 ? cycleView : nil
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return currentIndex == 1 ? bannerHeight + 20 : 0.1
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataSource[indexPath.row] as? CollectModel
        let images = model?.images
//        var identifer = ""
//        if images != nil && images!.count > 0{
//            identifer = cellIdentifer
//        }else{
//            identifer = noImgIdentifer
//        }
//        var cell : MyCollectNoImgCell = tableView.dequeueReusableCell(withIdentifier: identifer) as? MyCollectNoImgCell
//        if cell == nil {
//            cell
//        }
        
        var cell : MyCollectNoImgCell?
        if images == nil || images?.count == 0{
            cell = tableView.dequeueReusableCell(withIdentifier: noImgIdentifer) as? MyCollectNoImgCell
            cell?.deleteBtn.snp.updateConstraints({ (make) in
                make.bottom.equalTo(25)
            })
        }else if images?.count == 1{
            cell = tableView.dequeueReusableCell(withIdentifier: oneImgIdentifer) as? MyBlogOneImageCell
          
        }else{
            cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifer) as! MyCollectCell
            cell?.deleteBtn.snp.updateConstraints({ (make) in
                make.bottom.equalTo(25)
            })
        }
//        if images != nil && images?.count == 1{
//            cell?.deleteBtn.snp.updateConstraints({ (make) in
//                make.bottom.equalTo(25)
//            })
//        }
       
        cell?.contentView.backgroundColor = .white
        cell?.deleteBtn.setTitle("", for: .normal)
//        cell?.deleteBtn.tag = 401 + indexPath.row
        cell!.setCollectInfo(model: model!)
        cell?.selectionStyle = .none
        return cell!
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.didClickRow != nil {
            if let model = self.dataSource[indexPath.row] as? CollectModel{
                if let blogId = model.objectId{
                    self.didClickRow!(0,blogId)

                }

            }

        }
    }
}
